from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *

import re

from django.core.paginator import Paginator


class CateView(APIView):
    def post(self, request):
        if CateModel.objects.filter(name=request.data.get('name')):
            return Response({'msg': '该分类已存在', 'code': 400})
        ser = CateSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request):
        cate_obj = CateModel.objects.all()
        ser = CateSer(cate_obj, many=True)
        return Response(ser.data)


class GoodsView(APIView):
    def post(self, request):
        name = request.data.get('name')
        price = request.data.get('price')
        if not re.match(r'\d{1,5}$', price):
            return Response({'msg': '价格错误', 'code': 400})
        goods_obj = GoodsModel.objects.filter(name=name).first()
        if goods_obj:
            return Response({'msg': '商品已存在', 'code': 400})
        ser = GoodsSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request):
        cid = request.GET.get('cid')
        pid = request.GET.get('pid')
        cate_obj = CateModel.objects.get(pk=cid)
        goods_obj = GoodsModel.objects.filter(cate=cate_obj)
        paginato = Paginator(goods_obj, 3)
        paged = paginato.page(pid)
        ser = GoodsSer(paged, many=True)
        return Response({
            'page_sum': paginato.num_pages,
            'page_list': [i for i in paginato.page_range],
            'data': ser.data
        })


class OrderView(APIView):
    def post(self, request):
        ser = OrderSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})
